import 'package:efood_multivendor/controller/auth_controller.dart';
import 'package:efood_multivendor/controller/cart_controller.dart';
import 'package:efood_multivendor/controller/restaurant_controller.dart';
import 'package:efood_multivendor/controller/user_controller.dart';
import 'package:efood_multivendor/data/model/response/cart_model.dart';
import 'package:efood_multivendor/data/model/response/product_model.dart';
import 'package:efood_multivendor/data/model/response/restaurant_model.dart';
import 'package:efood_multivendor/helper/date_converter.dart';
import 'package:efood_multivendor/helper/price_converter.dart';
import 'package:efood_multivendor/helper/route_helper.dart';
import 'package:efood_multivendor/helper/size_config.dart';
import 'package:efood_multivendor/util/dimensions.dart';
import 'package:efood_multivendor/util/styles.dart';
import 'package:efood_multivendor/view/base/age_dialog.dart';
import 'package:efood_multivendor/view/base/custom_image.dart';
import 'package:efood_multivendor/view/base/not_available_widget.dart';
import 'package:efood_multivendor/view/base/not_logged_in_screen.dart';
import 'package:efood_multivendor/view/base/quantity_button.dart';
import 'package:efood_multivendor/view/screens/product/product_screen.dart';
import 'package:efood_multivendor/view/screens/restaurant/restaurant_screen.dart';
import 'package:firebase_analytics/firebase_analytics.dart';
import 'package:flutter/material.dart';
import 'package:flutter_feather_icons/flutter_feather_icons.dart';
import 'package:get/get.dart';

import '../../controller/splash_controller.dart';

class ProductWidget extends StatelessWidget {
  final Product? product;
  final Restaurant? restaurant;
  final bool isRestaurant;
  final int index;
  final int length;
  final bool inRestaurant;
  final bool isCampaign;
  final String? price;
  final bool fromRestaurant;
  final bool formSuggestion;
  final bool formCategory;
  ProductWidget(
      {required this.product,
      required this.isRestaurant,
      required this.restaurant,
      required this.index,
      required this.length,
      required this.fromRestaurant,
      this.formSuggestion = false,
      this.formCategory = false,
      this.inRestaurant = false,
      this.isCampaign = false,
      this.price});
  static const int YearInHour = 8760;

  @override
  Widget build(BuildContext context) {
    double _discount = 0;
    String _discountType;
    double _productDiscount = 0;
    double _restaurantDiscount = 0;
    bool _isAvailable;
    int _avgPrice = 147;
    int distance = 500;
    String imageExecuted =
        '${isRestaurant ? restaurant?.logo : product?.image}';
    CartModel? _cartModel;
    bool hasAddons = false;

    if (isRestaurant) {
      bool _isClosedToday = Get.find<RestaurantController>().isRestaurantClosed(
          true, restaurant?.active ?? false, restaurant?.offDay ?? '');

      _isAvailable = restaurant?.is_open == true &&
          restaurant?.active == true &&
          !_isClosedToday &&
          restaurant?.too_far != true;
    } else {
      hasAddons = product?.addOns?.isNotEmpty == true;

      _isAvailable =
          product?.is_open == true && product?.restaurantTooFar != true;

      _cartModel = CartModel(
          product?.price,
          product?.discountedItemPrice,
          [],
          product!.price! - product!.discountedItemPrice!,
          1,
          [],
          [],
          false,
          product,
          0);
    }

    return InkWell(
      onTap: () async {
        if (isRestaurant) {
          Get.toNamed(RouteHelper.getRestaurantRoute(restaurant!.id!),
              arguments: RestaurantScreen(restaurant: restaurant!));
          await FirebaseAnalytics.instance
              .logEvent(name: 'restaurant_from_home_clicked', parameters: {
            'restaurantID': restaurant!.id.toString(),
            'timestamp': DateConverter.getCurrentTimeInGmtPlus3().toString()
          });
        } else {
          Get.toNamed(RouteHelper.getProductRoute(product!.id!),
              arguments: ProductScreen(
                product: product!,
                fromCategory: formCategory,
                fromSuggestion: formSuggestion,
              ));
        }
      },
      child: Container(
        decoration: BoxDecoration(
          borderRadius: BorderRadius.circular(Dimensions.RADIUS_SMALL),
        ),
        child: Column(mainAxisAlignment: MainAxisAlignment.center, children: [
          Expanded(
              child: Padding(
            padding: EdgeInsets.symmetric(
                vertical: Dimensions.PADDING_SIZE_EXTRA_SMALL),
            child: Row(children: [
              ClipRRect(
                borderRadius: BorderRadius.circular(Dimensions.RADIUS_SMALL),
                child: Stack(children: [
                  CustomImage(
                    image:
                        '${isRestaurant ? restaurant!.logo : product!.image}',
                    height: 12.h,
                    width: 12.h,
                    fit: BoxFit.cover,
                  ),
                  _isAvailable
                      ? SizedBox()
                      : NotAvailableWidget(
                          isTooFar: isRestaurant == true
                              ? restaurant!.too_far!
                              : product!.restaurantTooFar!,
                          isRestaurant: isRestaurant,
                          fontSize: Dimensions.fontSizeLarge * 0.8,
                        ),
                ]),
              ),
              SizedBox(width: Dimensions.PADDING_SIZE_SMALL),
              Expanded(
                child: Column(
                    crossAxisAlignment: CrossAxisAlignment.start,
                    mainAxisAlignment: MainAxisAlignment.spaceAround,
                    children: [
                      Spacer(),
                      Row(
                        children: [
                          Expanded(
                            flex: 8,
                            child: Text(
                              (isRestaurant
                                      ? restaurant?.name
                                      : product?.name) ??
                                  '',
                              style: sfBold.copyWith(
                                  fontSize: isRestaurant
                                      ? Dimensions.fontSizeLarge * 1.1
                                      : Dimensions.fontSizeLarge),
                              maxLines: !isRestaurant
                                  ? product?.isHalal == 1
                                      ? 1
                                      : 2
                                  : 2,
                              overflow: TextOverflow.ellipsis,
                            ),
                          ),
                          Spacer(),
                          isRestaurant
                              ? restaurant?.avgRating != 0
                                  ? RatingTag(rating: restaurant!.avgRating!)
                                  : SizedBox()
                              : SizedBox(),
                        ],
                      ),
                      SizedBox(
                          height: isRestaurant
                              ? Dimensions.PADDING_SIZE_EXTRA_SMALL
                              : 0),
                      isRestaurant
                          ? Row(
                              children: [
                                Container(
                                  padding: EdgeInsets.all(
                                      Dimensions.PADDING_SIZE_SMALL / 2),
                                  decoration: BoxDecoration(
                                      borderRadius: BorderRadius.circular(
                                          Dimensions.RADIUS_SMALL),
                                      border: Border.all(color: Colors.red)),
                                  child: Text(
                                    '${"around".tr} ${restaurant!.distance} ${"around_amharic".tr}',
                                    style: sfBold.copyWith(
                                        fontSize: Dimensions.fontSizeSmall,
                                        color: Colors.red),
                                  ),
                                ),
                                SizedBox(
                                    width: Dimensions.PADDING_SIZE_EXTRA_SMALL *
                                        1.5),
                                Container(
                                  padding: EdgeInsets.all(
                                      Dimensions.PADDING_SIZE_SMALL / 2),
                                  decoration: BoxDecoration(
                                      borderRadius: BorderRadius.circular(
                                          Dimensions.RADIUS_SMALL),
                                      border: Border.all(color: Colors.red)),
                                  child: Text(
                                    "${"around".tr} ${restaurant!.deliveryTime} ${"min".tr} ${"around_amharic".tr}",
                                    style: sfBold.copyWith(
                                        fontSize: Dimensions.fontSizeSmall,
                                        color: Colors.red),
                                  ),
                                ),
                              ],
                            )
                          : SizedBox(),
                      Spacer(),
                      !isRestaurant
                          ? SizedBox(
                              child: Text(
                                product?.restaurantName ?? '',
                                maxLines: product?.isHalal == 1 ? 1 : 2,
                                overflow: TextOverflow.ellipsis,
                                style: sfMedium.copyWith(
                                    fontWeight: FontWeight.w400,
                                    fontSize: 13,
                                    color: Colors.grey),
                              ),
                            )
                          : Row(
                              children: [
                                Text(
                                  "${"avg".tr} ${PriceConverter.convertPrice((restaurant!.avgPrice)!.toDouble(), asFixed: 0)} ${"per_person".tr}",
                                  style: sfRegular.copyWith(
                                    fontSize: Dimensions.fontSizeDefault,
                                    color: Colors.grey,
                                    // decoration: TextDecoration.lineThrough,
                                    // decorationColor:
                                    //     Theme.of(context).disabledColor,
                                  ),
                                  maxLines: 1,
                                  overflow: TextOverflow.ellipsis,
                                ),
                              ],
                            ),
                      Spacer(),
                      isRestaurant
                          ? SizedBox()
                          : product?.isHalal == 1
                              ? HalalTag()
                              : SizedBox(),
                      isRestaurant
                          ? SizedBox()
                          : product?.veg == 1
                              ? FastingTag()
                              : SizedBox(),
                      Expanded(
                        child: SizedBox(
                          height: 2,
                        ),
                      ),
                      isRestaurant
                          ? Row(
                              children: [
                                Text(
                                  "${"delivery_fee".tr} ${"starting_from".tr} ${PriceConverter.convertPrice(restaurant!.deliveryFee!, asFixed: 0)} ${"jemro".tr}",
                                  style: sfRegular.copyWith(
                                    fontSize: Dimensions.fontSizeDefault,
                                    color: Colors.grey,
                                  ),
                                  maxLines: 1,
                                  overflow: TextOverflow.ellipsis,
                                ),
                              ],
                            )
                          : Row(children: [
                              Text(
                                product?.discountedItemPrice.toString() ?? '',
                                style: sfMedium.copyWith(
                                    fontSize: Dimensions.fontSizeLarge),
                              ),
                              SizedBox(
                                  width: product!.discountedItemPrice! <
                                          product!.price!
                                      ? Dimensions.PADDING_SIZE_EXTRA_SMALL
                                      : 0),
                              product!.discountedItemPrice! < product!.price!
                                  ? Text(
                                      PriceConverter.convertPrice(
                                          product!.price!),
                                      style: sfMedium.copyWith(
                                        fontSize: Dimensions.fontSizeExtraSmall,
                                        color: Theme.of(context).disabledColor,
                                        decoration: TextDecoration.lineThrough,
                                        decorationColor:
                                            Theme.of(context).disabledColor,
                                      ),
                                    )
                                  : SizedBox(),
                            ]),
                      Expanded(
                          child: SizedBox(
                        width: 15,
                      ))
                    ]),
              ),
              !isRestaurant
                  ? GetBuilder<CartController>(builder: (cartController) {
                      int qty = cartController.getQuantity(product);

                      return qty == 0
                          ? GestureDetector(
                              onTap: () {
                                if (!_isAvailable) {
                                  return;
                                } else {
                                  Function() callback = () {
                                    if (hasAddons &&
                                        cartController.totalItemsInCart <
                                            Get.find<SplashController>()
                                                .configModel!
                                                .limitPerItemValue!) {
                                      Get.toNamed(
                                          RouteHelper.getProductRoute(
                                              product!.id!),
                                          arguments: ProductScreen(
                                            product: product!,
                                            fromCategory: formCategory,
                                            fromSuggestion: formSuggestion,
                                          ));
                                    }
                                    if (!fromRestaurant) {
                                      if (formSuggestion) {
                                        cartController.setCurrentSuggestion(
                                            _cartModel!.product!.restaurantId!);
                                        if (cartController.previousSuggestion !=
                                            0) {
                                          if (cartController
                                                  .previousSuggestion !=
                                              cartController
                                                  .currentSuggestion) {
                                            Get.find<CartController>()
                                                .clearPreviousRestaurant(
                                                    cartController
                                                        .previousSuggestion);

                                            Get.find<CartController>()
                                                .addToCart(_cartModel);

                                            cartController
                                                .setPreviousSuggestion(
                                                    _cartModel.product!
                                                        .restaurantId!);
                                          } else {
                                            Get.find<CartController>()
                                                .addToCart(_cartModel);
                                            cartController
                                                .setPreviousSuggestion(
                                                    _cartModel.product!
                                                        .restaurantId!);
                                          }
                                        } else {
                                          Get.find<CartController>()
                                              .addToCart(_cartModel);
                                          cartController.setPreviousSuggestion(
                                              _cartModel
                                                  .product!.restaurantId!);
                                        }
                                      } else {
                                        cartController.setCurrentCategory(
                                            _cartModel!.product!.restaurantId!);
                                        if (cartController.previousCategory !=
                                            0) {
                                          if (cartController.previousCategory !=
                                              cartController.currentCategory) {
                                            Get.find<CartController>()
                                                .clearPreviousRestaurant(
                                                    cartController
                                                        .previousCategory);

                                            Get.find<CartController>()
                                                .addToCart(_cartModel);

                                            cartController.setPreviousCategory(
                                                _cartModel
                                                    .product!.restaurantId!);
                                          } else {
                                            Get.find<CartController>()
                                                .addToCart(_cartModel);
                                            cartController.setPreviousCategory(
                                                _cartModel
                                                    .product!.restaurantId!);
                                          }
                                        } else {
                                          Get.find<CartController>()
                                              .addToCart(_cartModel);
                                          cartController.setPreviousCategory(
                                              _cartModel
                                                  .product!.restaurantId!);
                                        }
                                      }
                                    } else {
                                      if (Get.find<CartController>()
                                          .existAnotherRestaurantProduct(
                                              _cartModel!
                                                  .product!.restaurantId!)) {
                                        Get.find<CartController>()
                                            .addToCart(_cartModel);
                                      } else {
                                        Get.find<CartController>()
                                            .addToCart(_cartModel);
                                      }
                                    }
                                  };

                                  if (Get.find<AuthController>().isLoggedIn() &&
                                      product!.is_alcohol!) {
                                    if (Get.find<UserController>()
                                            .userInfoModel
                                            ?.birthDate
                                            ?.isNotEmpty ==
                                        true) {
                                      DateTime birthday = DateTime.parse(
                                          Get.find<UserController>()
                                              .userInfoModel!
                                              .birthDate!);
                                      if ((DateTime.now()
                                                  .difference(birthday)
                                                  .inHours /
                                              YearInHour) >=
                                          21) {
                                        callback();
                                      } else {
                                        Get.dialog(AgeDialog(
                                          callback: callback,
                                        ));
                                      }
                                    } else {
                                      Get.dialog(AgeDialog(
                                        callback: callback,
                                      ));
                                    }
                                  } else if (!Get.find<AuthController>()
                                          .isLoggedIn() &&
                                      product?.is_alcohol == true) {
                                    Get.dialog(
                                        Scaffold(body: NotLoggedInScreen()));
                                  } else {
                                    callback();
                                  }
                                }
                              },
                              child: Container(
                                decoration: BoxDecoration(
                                    borderRadius: BorderRadius.all(
                                        Radius.circular(Dimensions
                                            .PADDING_SIZE_EXTRA_SMALL)),
                                    border: Border.all(
                                        color: _isAvailable
                                            ? Theme.of(context)
                                                .colorScheme
                                                .secondary
                                            : Theme.of(context).disabledColor)),
                                width: 23.w,
                                height: 4.5.h,
                                margin: EdgeInsets.only(right: 9),
                                child: Align(
                                  alignment: Alignment.center,
                                  child: Row(
                                    mainAxisAlignment: MainAxisAlignment.center,
                                    crossAxisAlignment:
                                        CrossAxisAlignment.center,
                                    children: [
                                      Icon(
                                        Icons.add,
                                        size: 25,
                                        color: _isAvailable
                                            ? Theme.of(context)
                                                .colorScheme
                                                .secondary
                                            : Theme.of(context).disabledColor,
                                      ),
                                      Text("add".tr,
                                          style: sfRegular.copyWith(
                                              color: _isAvailable
                                                  ? Theme.of(context)
                                                      .colorScheme
                                                      .secondary
                                                  : Theme.of(context)
                                                      .disabledColor,
                                              fontSize: 15))
                                    ],
                                  ),
                                ),
                              ),
                            )
                          : Row(
                              children: [
                                QuantityButton(
                                    isIncrement: false,
                                    isActive: _isAvailable,
                                    onTap: () => _isAvailable
                                        ? cartController.removeFromCart(
                                            _cartModel!, isRestaurant)
                                        : () {}),
                                Text(
                                    cartController
                                        .getQuantity(product)
                                        .toString(),
                                    style: sfMedium.copyWith(
                                        fontSize:
                                            Dimensions.fontSizeExtraLarge)),
                                QuantityButton(
                                    isIncrement: true,
                                    isActive: _isAvailable,
                                    onTap: () {
                                      if (!_isAvailable) {
                                        return;
                                      }
                                      if (Get.find<CartController>()
                                          .existAnotherRestaurantProduct(
                                              _cartModel!
                                                  .product!.restaurantId!)) {
                                        Get.find<CartController>()
                                            .addToCart(_cartModel);
                                      } else {
                                        Get.find<CartController>()
                                            .addToCart(_cartModel);
                                      }
                                    }),
                              ],
                            );
                    })
                  : SizedBox(),
            ]),
          )),
          SizedBox(
            height: 0,
            child: Padding(
              padding: EdgeInsets.only(left: 90),
              child: Divider(
                  color: index == length - 1
                      ? Colors.transparent
                      : Theme.of(context).disabledColor),
            ),
          ),
        ]),
      ),
    );
  }
}

class RatingTag extends StatefulWidget {
  final double rating;
  RatingTag({Key? key, required this.rating}) : super(key: key);

  @override
  State<RatingTag> createState() => _RatingTagState();
}

class _RatingTagState extends State<RatingTag> {
  @override
  Widget build(BuildContext context) {
    return Center(
      child: Row(
        children: [
          Icon(Icons.star,
              size: 1.6.h, color: Theme.of(context).colorScheme.secondary),
          SizedBox(
            width: 1.w,
          ),
          Text(
            widget.rating.toStringAsFixed(1),
            style: sfRegular.copyWith(
              color: Colors.black,
            ),
            textAlign: TextAlign.center,
          ),
        ],
      ),
    );
  }
}

class HalalTag extends StatefulWidget {
  HalalTag({Key? key}) : super(key: key);

  @override
  State<HalalTag> createState() => _HalalTagState();
}

class _HalalTagState extends State<HalalTag> {
  @override
  Widget build(BuildContext context) {
    return Container(
      padding: EdgeInsets.symmetric(horizontal: 0.5.h, vertical: 0.7.h),
      child: Center(
        child: Row(
          children: [
            Icon(
              FeatherIcons.moon,
              color: Colors.green,
              size: 18,
            ),
            SizedBox(
              width: 1.w,
            ),
            Text(
              "halal".tr,
              style: sfRegular.copyWith(
                color: Colors.black,
              ),
              textAlign: TextAlign.center,
            ),
            SizedBox(
              width: 1.w,
            ),
          ],
        ),
      ),
    );
  }
}

class FastingTag extends StatefulWidget {
  FastingTag({Key? key}) : super(key: key);

  @override
  State<FastingTag> createState() => _FastingTagState();
}

class _FastingTagState extends State<FastingTag> {
  @override
  Widget build(BuildContext context) {
    return Container(
      padding: EdgeInsets.symmetric(horizontal: 0.5.h, vertical: 0.7.h),
      child: Center(
        child: Row(
          children: [
            Container(
              height: 2.0.h,
              width: 2.0.h,
              decoration: BoxDecoration(
                borderRadius: BorderRadius.circular(3),
                border: Border.all(
                  width: 1,
                  color: Theme.of(context).secondaryHeaderColor,
                ),
              ),
              child: Padding(
                padding: EdgeInsets.all(4),
                child: Container(
                  height: 0.4.h,
                  width: 0.4.h,
                  decoration: BoxDecoration(
                    borderRadius: BorderRadius.circular(10),
                    color: Theme.of(context).secondaryHeaderColor,
                  ),
                ),
              ),
            ),
            SizedBox(
              width: 1.w,
            ),
            Text(
              "fasting".tr,
              style: sfRegular.copyWith(
                color: Colors.black,
              ),
              textAlign: TextAlign.center,
            ),
            SizedBox(
              width: 1.w,
            ),
          ],
        ),
      ),
    );
  }
}
